package peppa.george.org.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import peppa.george.base.Util.AjaxResult;
import peppa.george.base.Util.PageUtil;
import peppa.george.base.query.BaseQuery;
import peppa.george.org.Service.PicUserService;
import peppa.george.org.domain.PicUser;
import peppa.george.org.domain.User;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/picUser")
public class PicUserController {
    @Autowired
    PicUserService picUserService;

    @PostMapping
    public AjaxResult fileUploadAndUpdate(@RequestBody MultipartFile file,HttpServletRequest request,PicUser picUser) throws IOException {
        //获取文件真实名 : file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
        System.out.println(uploadFileName);
        uploadFileName = UUID.randomUUID().toString().replace("-", "") + uploadFileName;
        System.out.println("上传文件名 : " + uploadFileName);
        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //realPath.delete(); 文件删除
        //
        System.out.println("上传文件保存地址：" + realPath);

        InputStream is = file.getInputStream(); //文件输入流
        //文件输出流
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
        //复制
        IOUtils.copy(is, os);
        os.close();
        is.close();
        User user = (User) request.getSession().getAttribute("user");
        picUser.setPicAddress(path);
        picUser.setSubmitPerson(user.getUsername());
        if(picUser.getId()==null){
            picUserService.save(picUser);
        }else {
           picUserService.update(picUser);
        }
        return AjaxResult.me().success();
    }

    @DeleteMapping
    public AjaxResult fileDel(Long id){
        picUserService.remove(id);
        return AjaxResult.me().success();
    }

    @PutMapping
    public PageUtil<PicUser> list(@RequestBody BaseQuery page){
        PageUtil<PicUser> picUserPageUtil = picUserService.QueryData(page);
        return picUserPageUtil;
    }
    @GetMapping("/list")
    public List<PicUser> list1(){
        return picUserService.findall();
    }

}
